package com.schillerchina.baselibrary.utils;

import android.graphics.drawable.Drawable;
import android.util.Base64;

import androidx.annotation.StringRes;
import androidx.core.content.ContextCompat;

import com.schillerchina.baselibrary.network.App;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

/**
 * @author zhangzhiguo
 * @date 2019-08-05 09:39
 * @Description: 字符串工具类，提供一些字符串相关的便捷方法
 */
public class StringUtils {

    /**
     * 精确到指定位数字符串
     *
     * @param d     要格式化的数字
     * @param scale 指定精度位数
     * @return
     */
    public static String format(double d, int scale) {
        BigDecimal bigDecimal = new BigDecimal(d);
        bigDecimal = bigDecimal.setScale(scale, BigDecimal.ROUND_HALF_UP);
        return bigDecimal.toString();
    }

    /**
     * 保留三位小数
     *
     * @param d
     * @return
     */
    public static String mFormat3(double d) {
        DecimalFormat dFormat = new DecimalFormat();
        dFormat.setRoundingMode(RoundingMode.HALF_UP);
        dFormat.applyPattern("#0.000");
        return dFormat.format(d * 1000 / 1000.0);
    }

    public static String mFormat3(String d) {
        try {
            double dv = Double.valueOf(d);
            DecimalFormat dFormat = new DecimalFormat();
            dFormat.setRoundingMode(RoundingMode.HALF_UP);
            dFormat.applyPattern("#0.000");
            return dFormat.format(dv * 1000 / 1000.0);
        } catch (Exception e) {
            LogUtil.e(e);
            return Symbols.DASH;
        }
    }

    /**
     * 保留二位小数
     *
     * @param d
     * @return
     */
    public static String mFormat2(double d) {
        DecimalFormat dFormat = new DecimalFormat();
        dFormat.setRoundingMode(RoundingMode.HALF_UP);
        dFormat.applyPattern("#0.00");
        return dFormat.format(d * 100 / 100.0);
    }
//    public static String mFormat2(float d) {
//        DecimalFormat dFormat = new DecimalFormat();
//        dFormat.setRoundingMode(RoundingMode.HALF_UP);
//        dFormat.applyPattern("#0.00");
//        return dFormat.format(d * 100 / 100.0);
//    }

    /**
     * 保留一位小数
     *
     * @param d
     * @return
     */
    public static String mFormat1(double d) {
        DecimalFormat dFormat = new DecimalFormat();
        dFormat.setRoundingMode(RoundingMode.HALF_UP);
        dFormat.applyPattern("#0.0");
        return dFormat.format(d * 10 / 10.0);
    }

    public static String mFormat1(String d) {
        try {
            double dv = Double.valueOf(d);
            DecimalFormat dFormat = new DecimalFormat();
            dFormat.setRoundingMode(RoundingMode.HALF_UP);
            dFormat.applyPattern("#0.0");
            return dFormat.format(dv * 10 / 10.0);
        } catch (Exception e) {
            LogUtil.e(e);
            return Symbols.DASH;
        }
    }

    /**
     * BASE 64 字符编码
     *
     * @param s 需要编码字符串
     * @return
     */
    public static String getBASE64(String s) {
        return s == null ? null : Base64.encodeToString(s.getBytes(), Base64.DEFAULT);
    }

    /**
     * is null or its length is 0
     * <p>
     * <pre>
     * isEmpty(null) = true;
     * isEmpty(&quot;&quot;) = true;
     * isEmpty(&quot;  &quot;) = false;
     * </pre>
     *
     * @param str str
     * @return if string is null or its size is 0, return true, else return
     * false.
     */
    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() == 0 || "null".equals(str.toLowerCase());
    }

    /**
     * 是否是float类型
     */
    public static boolean isNumber(String str) {
        if (isEmpty(str)) {
            return false;
        }
        try {
            Float.valueOf(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 是否全是数字
     */
    public static boolean isAllDigital(char[] chars) {
        boolean result = true;
        for (int w = 0; w < chars.length; w++) {
            if (!Character.isDigit(chars[w])) {
                result = false;
                break;
            }
        }
        return result;
    }

    public static boolean isAllDigital(String str) {
        return isAllDigital(str.toCharArray());
    }

    /**
     * get length of CharSequence
     * <p>
     * <pre>
     * length(null) = 0;
     * length(\"\") = 0;
     * length(\"abc\") = 3;
     * </pre>
     *
     * @param str str
     * @return if str is null or empty, return 0, else return {@link
     * CharSequence#length()}.
     */
    public static int length(CharSequence str) {

        return str == null ? 0 : str.length();
    }


    /**
     * 字符串数组中删除某个字符串
     *
     * @param strings
     * @param toBeRemoved
     * @return
     */
    public static String[] remove(String[] strings, String toBeRemoved) {
        List<String> list = new ArrayList<>(Arrays.asList(strings));
        list.remove(toBeRemoved);
        return list.toArray(new String[]{});
    }


    public static String[] addToFirst(String[] strings, String toBeAdded) {
        List<String> list = new ArrayList<>(Arrays.asList(strings));
        list.add(0, toBeAdded);
        return list.toArray(new String[]{});
    }

    /**
     * 字符串翻转
     *
     * @param resource
     * @return
     */
    public static String reverse(String resource) {
        StringBuffer sb = new StringBuffer(resource);
        sb.reverse();
        return sb.toString();
    }

    /**
     * 字符资源转换为字符串
     *
     * @param resId
     * @return
     */
    public static String getResourceString(@StringRes int resId) {
        return App.getContext().getString(resId);
    }

    /**
     * 字符资源转换为颜色值
     *
     * @param resId 颜色资源id
     * @return
     */
    public static int getResourceColor(int resId) {
        return ContextCompat.getColor(App.getContext(), resId);
    }

    /**
     * 获取drawable资源
     *
     * @param resId drawable资源id
     * @return
     */
    public static Drawable getResourceDrawable(int resId) {
        return ContextCompat.getDrawable(App.getContext(), resId);
    }

    /**
     * 将字符串按指定分隔符拆分字符list，默认分隔符是“;”
     *
     * @param str
     * @return
     */
    public static List<String> splitToArray(String str) {
        return splitToArray(str, Symbols.SEMICOLON);
    }

    public static List<String> splitToArray(String str, String delimiter) {
        return new ArrayList<String>(Arrays.asList(str.split(delimiter)));
    }

    /**
     * List 转 字符串数组
     *
     * @param list
     * @return
     */
    public static String[] getArray(List<String> list) {
        String[] arr = new String[list.size()];
        list.toArray(arr);

        return arr;
    }


    /**
     * 以分隔符连接字符串列表，默认的连接符";"
     *
     * @param strList 字符串列表
     * @return
     */
    public static String join(List<String> strList) {
        return join(strList, Symbols.SEMICOLON);
    }

    public static String join(List<String> strList, String delimiter) {
        if (strList == null || strList.size() == 0) {
            return "";
        }
        StringBuilder builder = new StringBuilder();
        for (String s : strList) {
            builder.append(s).append(delimiter);
        }
        return builder.toString().substring(0, builder.length() - delimiter.length());
    }


    /**
     * 判断字符串是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }


    public static short[] ArrayListToShort(ArrayList<Short> list) {
        short[] array = new short[2001];
        try{
            for (int i = 0; i < list.size(); i++) {
                array[i] = list.get(i);
            }
        }catch (Exception e){

        }
        return array;
    }


    public static float[] ArrayListToFloat(ArrayList<Float> list) {
        float[] array = new float[2001];
        try{
            for (int i = 0; i < list.size(); i++) {
                array[i] = list.get(i);
            }
        }catch (Exception e){

        }
        return array;
    }


    /**
     * 字符数截取
     *
     * @param str
     * @param subLength
     * @return
     */
    public static String subString(String str, int subLength) {
        int n = 0;
        int i = 0;
        int j = 0;
        int byteNum = subLength * 2;
        boolean flag = true;
        if (str == null) {
            return "";
        }

        for (i = 0; i < str.length(); i++) {
            if ((int) (str.charAt(i)) < 128) {
                n += 1;
            } else {
                n += 2;
            }
            if (n > byteNum && flag) {
                j = i;
                flag = false;
            }
            if (n >= byteNum + 2) {
                break;
            }
        }

        if (n >= byteNum + 2 && i != str.length() - 1) {
            str = str.substring(0, j);
            str += "...";
        }
        return str;
    }


    /**
     * 字符数截取
     *
     * @param data
     * @param sub
     * @return
     */
    public static String subString(String data, String sub) {
        if (data == null) {
            return null;
        }

        String channel1 = "";

        int i = 0;

        for (String str : data.split(sub)) {
            try {

//                String str=data.split(sub)[data.split(sub).length-1];

                String length = str.substring(0, 2);
                if (isNumeric(length)) {

                    String strData = data.substring(data.indexOf(str), data.indexOf(str) + Integer.valueOf(length) * 2 + 10);


                    String type = strData.substring(2, 4);
                    String operation = strData.substring(4, 6);
                    String cid = strData.substring(6, 8);
                    if (type.equals("10") && operation.equals("04") && cid.equals("90")) {

                        String dataBlock = strData.substring(8, 8 + Integer.valueOf(length) * 2);

//                        70 68 0C   6F A0 8C    3F 68 80   00 08 80
//                        channel 一:870
//                        channel 二:0C6
//                        channel 三:06F
//                        channel 四:8CA
//                        channel 五:83F
//                        channel 六:806
//                        channel 七:800
//                        channel 八:800

                        channel1 = dataBlock.substring(3, 4) + dataBlock.substring(0, 2);
//
//                        EcgGreenDaoBean ecgDbBean = new EcgGreenDaoBean();
//                        ecgDbBean.setChannel("1");
//                        ecgDbBean.setCurrentTime(String.valueOf(System.currentTimeMillis()));
//                        ecgDbBean.setEcgHexData(channel1);
////                        十六进制转十进制
//                        channel1 = String.valueOf(Long.parseLong(channel1, 16));
//                        ecgDbBean.setEcgDecData(channel1);
//
//                        ecgDbBean.setX(1f);
//                        ecgDbBean.setY(2f);
                        return channel1;


//                        daoSession.insert(ecgDbBean);
//                        for (int i = 0; i < 1000; i++) {
//
////                        ecgDbDao.insert(ecgDbBean);
//                        ecgDbDao.insert(ecgDbBean).subscribeOn(Schedulers.io()).
//                                observeOn(Schedulers.io()).
//                                subscribe(new CompletableObserver() {
//                                    @Override
//                                    public void onSubscribe(Disposable d) {
//                                    }
//
//                                    @Override
//                                    public void onComplete() {
//
////                                        db.close();
//                                    }
//
//                                    @Override
//                                    public void onError(Throwable e) {
//                                    }
//                                });


//                        String channel2=dataBlock.substring(4,6)+dataBlock.substring(2,3);
//
//                        String channel3=dataBlock.substring(9,10)+dataBlock.substring(6,8);
//                        String channel4=dataBlock.substring(10,12)+dataBlock.substring(8,9);
//
//                        String channel5=dataBlock.substring(15,16)+dataBlock.substring(12,14);
//                        String channel6=dataBlock.substring(16,18)+dataBlock.substring(14,15);
//                        String channel7=dataBlock.substring(21,22)+dataBlock.substring(18,20);
//                        String channel8=dataBlock.substring(22,24)+dataBlock.substring(20,21);

                    }
                }
            } catch (Exception e) {
            }
        }

        return channel1;
    }


    public static boolean subStringChannel(String data, String sub) {
        if (data == null) {
            ToastUtil.showToast("SD卡数据为空");
            return false;
        }
        data = data.trim();

//        7EC00001 003064 005DBD001FA5004793003FF9001BBF003AB5C00001
//        7E C00001 003044 005DA5 001F80 004721 003FB0 000040 0C1500 177440
        long channel1 = 0;
        for (String str : data.split(sub)) {
            for (int i = 0; i < 8; i++) {
                String count = "";
                if (str.length() == 48) {
//                if (str.substring(0, 6).equals("C00001")) {
//                    channel1 = str.substring(i*6, (i+1)*6);

                    channel1 = Long.parseLong(str.substring(i * 6, (i + 1) * 6), 16);

                    channel1 = channel1 & 0x00FFFFFF;

                    if (((channel1 >> 16) & 0x80) == 0x80) {
                        channel1 = channel1 + 0xFF000000;
                    }
                    count = count + "\n" + channel1;
//                }
                }
//                FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx" + i + ".txt", true, count);
//                if(i>=7){
//                    return true;
//                }
            }
        }

        return false;
    }


    int filterLength = 100;

    private static List<Float> filterList = new ArrayList<>();

    float[] filter35Hz = new float[filterLength];

    public static void subStringChannel1(String data) {

//        new Thread() {
//            public void run() {
        String count1 = "";
        String count2 = "";
        String count3 = "";
        String count4 = "";
        String count5 = "";
        String count6 = "";
        String count7 = "";
        String count8 = "";
//                long channel1;


        for (String str : data.split("FEFE0000")) {
            if (str.length() >= 32) {
                int channel1 = parseData(str.substring(0, 4));
                channel1 = channel1 * -1;
                int channel2 = parseData(str.substring(4, 8));
                channel2 = channel2 * -1;
                int channel3 = parseData(str.substring(8, 12));
                channel3 = channel3 * -1;
                int channel4 = parseData(str.substring(12, 16));
                int channel5 = parseData(str.substring(16, 20));

                int channel6 = parseData(str.substring(20, 24));
                channel6 = channel6 * -1;
                int channel7 = parseData(str.substring(24, 28));
                channel7 = channel7 * -1;
                int channel8 = parseData(str.substring(28, 32));
                channel8 = channel8 * -1;
                filterList.add(Float.valueOf(channel1));
                if (filterList.size() == 100) {
                    FilterUtils.filter35Hz(filterList);
                    filterList.clear();
                }
                count1 = count1 + channel1 + "\n";
                count2 = count2 + channel2 + "\n";
                count3 = count3 + channel3 + "\n";
                count4 = count4 + channel4 + "\n";
                count5 = count5 + channel5 + "\n";
                count6 = count6 + channel6 + "\n";
                count7 = count7 + channel7 + "\n";
                count8 = count8 + channel8 + "\n";
            }
        }
//        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx1.txt", true, count1+"\n" +count2+"\n" +count3+"\n" +count4+"\n" +count5+"\n" +count6+"\n" +count7+"\n" +count8);
        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx1.txt", true, count1);
        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx2.txt", true, count2);
        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx3.txt", true, count3);
        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx4.txt", true, count4);
        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx5.txt", true, count5);
        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx6.txt", true, count6);
        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx7.txt", true, count7);
        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx8.txt", true, count8);
        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx.txt", true, count1 + count2 + count3 + count4 + count5 + count6 + count7 + count8);
//            }
//        }.start();
    }

    private static int parseData(String channel) {
        int channel1 = Integer.parseInt(channel, 16);

        channel1 = channel1 & 0x0000FFFF;

        if (((channel1 >> 8) & 0x80) == 0x80) {
            channel1 = channel1 + 0xFFFF0000;
        }
        return channel1;
    }


    public static String subStringChannel(String data) {
        if (data == null) {
            return null;
        }

//        new Thread() {
//            public void run() {
        String count = "";
        String channel1 = "";
        for (String str : data.split("7E7E")) {
            if (str.length() > 6) {
//            channel1 = AsciiUtil.AsciiStringToString(str.substring(0,6));
                channel1 = String.valueOf(Long.parseLong(str.substring(6, 12), 16));
                count = count + "\n" + channel1;
            }
        }
        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx.txt", true, count);
//            }
//        }.start();


        return null;
    }

    public static String getTimeDisplayNameNormal(long ctimelong) {
        String r = "";

        Calendar currentTime = Calendar.getInstance();
        long currentTimelong = System.currentTimeMillis();

        Calendar publicCal = Calendar.getInstance();
        publicCal.setTimeInMillis(ctimelong);

        long timeDelta = currentTimelong - ctimelong;

        if (timeDelta < 60 * 1000L) {

            r = "刚刚";

        } else if (timeDelta < 60 * 60 * 1000L) {

            r = timeDelta / (60 * 1000L) + "分钟前";

        } else if (timeDelta < 24 * 60 * 60 * 1000L) {

            if (currentTime.get(Calendar.DAY_OF_YEAR) == publicCal.get(Calendar.DAY_OF_YEAR)) {
                r = timeDelta / (60 * 60 * 1000L) + "小时前";
            } else {
                r = "昨天";
            }

        } else if (timeDelta < 2 * 24 * 60 * 60 * 1000L) {

            if (currentTime.get(Calendar.DAY_OF_YEAR) == publicCal.get(Calendar.DAY_OF_YEAR) + 1) {
                r = "昨天";
            } else {
                r = "前天";
            }

        } else if (timeDelta < 3 * 24 * 60 * 60 * 1000L) {

            if (currentTime.get(Calendar.DAY_OF_YEAR) == publicCal.get(Calendar.DAY_OF_YEAR) + 2) {
                r = "前天";
            } else {
                r = new SimpleDateFormat("yy年MM月dd日", Locale.CHINA).format(ctimelong);
            }
        } else {
            r = new SimpleDateFormat("yy年MM月dd日", Locale.CHINA).format(ctimelong);
        }
        return r;
    }

    public static String getTimeDisplayNameCompact(long ctimelong) {
        String r = "";

        Calendar currentTime = Calendar.getInstance();
        long currentTimelong = System.currentTimeMillis();

        Calendar publicCal = Calendar.getInstance();
        publicCal.setTimeInMillis(ctimelong);

        long timeDelta = currentTimelong - ctimelong;

        if (timeDelta <= 0L) {

            r = "刚刚";

        } else if (timeDelta < 60 * 1000L) {

            r = timeDelta / 1000L + "秒前";

        } else if (timeDelta < 60 * 60 * 1000L) {

            r = timeDelta / (60 * 1000L) + "分钟前";

        } else if (timeDelta < 24 * 60 * 60 * 1000L) {

            // if (currentTime.get(Calendar.DAY_OF_YEAR) ==
            // publicCal.get(Calendar.DAY_OF_YEAR)) {
            r = timeDelta / (60 * 60 * 1000L) + "小时前";
            // } else {
            // r = "昨天 " + new SimpleDateFormat("HH:mm").format(ctimelong);
            // }

        } else if (timeDelta < 2 * 24 * 60 * 60 * 1000L) {

            if (currentTime.get(Calendar.DAY_OF_YEAR) == publicCal.get(Calendar.DAY_OF_YEAR) + 1) {
                r = "昨天" + new SimpleDateFormat("HH:mm").format(ctimelong);
            } else {
                r = "前天" + new SimpleDateFormat("HH:mm").format(ctimelong);
            }

        } else if (timeDelta < 3 * 24 * 60 * 60 * 1000L) {

            if (currentTime.get(Calendar.DAY_OF_YEAR) == publicCal.get(Calendar.DAY_OF_YEAR) + 2) {
                r = "前天" + new SimpleDateFormat("HH:mm").format(ctimelong);
            } else {
                r = new SimpleDateFormat("MM月dd日").format(ctimelong);
            }

        } else {
            r = new SimpleDateFormat("MM月dd日").format(ctimelong);
        }
        return r;
    }


    private static String lastStr;

    public static void subStringChannel2(String data) {

//        new Thread() {
//            public void run() {
        String count1 = "";
        String count2 = "";
        String count3 = "";
        String count4 = "";
        String count5 = "";
        String count6 = "";
        String count7 = "";
        String count8 = "";
//                long channel1;
        String[] ecgDatas = data.split("FEFE0000");
        if (lastStr != null && ecgDatas[0].length() < 32 && lastStr.length() > 0) {
            String ecgStr = lastStr + ecgDatas[0];
            if (ecgStr.length() >= 32) {
                int channel1 = parseData(ecgStr.substring(0, 4));
                int channel2 = parseData(ecgStr.substring(4, 8));
                int channel3 = parseData(ecgStr.substring(8, 12));
                int channel4 = parseData(ecgStr.substring(12, 16));
                int channel5 = parseData(ecgStr.substring(16, 20));
                int channel6 = parseData(ecgStr.substring(20, 24));
                int channel7 = parseData(ecgStr.substring(24, 28));
                int channel8 = parseData(ecgStr.substring(28, 32));
                count1 = count1 + "\n" + channel1;
                count2 = count2 + "\n" + channel2;
                count3 = count3 + "\n" + channel3;
                count4 = count4 + "\n" + channel4;
                count5 = count5 + "\n" + channel5;
                count6 = count6 + "\n" + channel6;
                count7 = count7 + "\n" + channel7;
                count8 = count8 + "\n" + channel8;
            }
        }

        if (ecgDatas[ecgDatas.length - 1].length() < 32) {
            lastStr = ecgDatas[ecgDatas.length - 1];
        }


        for (String str : ecgDatas) {
            if (str.length() >= 32) {
                int channel1 = parseData(str.substring(0, 4));
                int channel2 = parseData(str.substring(4, 8));
                int channel3 = parseData(str.substring(8, 12));
                int channel4 = parseData(str.substring(12, 16));
                int channel5 = parseData(str.substring(16, 20));
                int channel6 = parseData(str.substring(20, 24));
                int channel7 = parseData(str.substring(24, 28));
                int channel8 = parseData(str.substring(28, 32));
                count1 = count1 + "\n" + channel1;
                count2 = count2 + "\n" + channel2;
                count3 = count3 + "\n" + channel3;
                count4 = count4 + "\n" + channel4;
                count5 = count5 + "\n" + channel5;
                count6 = count6 + "\n" + channel6;
                count7 = count7 + "\n" + channel7;
                count8 = count8 + "\n" + channel8;
            }
        }
//        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx1.txt", true, count1);
//        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx2.txt", true, count2);
//        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx3.txt", true, count3);
//        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx4.txt", true, count4);
//        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx5.txt", true, count5);
//        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx6.txt", true, count6);
//        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx7.txt", true, count7);
//        FileUtils.saveStrToSD(FileUtils.getSDCardRoot(), "/ecg_jx8.txt", true, count8);
//            }
//        }.start();
    }

}
